<template>
  <view class="history-orders-page">
    <!-- 顶部导航栏 -->
    <uni-nav-bar 
      :border="false"
      background-color="#ffffff"
      color="#333333"
      title="历史接单"
      left-icon="left"
      @clickLeft="goBack"
    >
      <template #right>
        <view class="nav-right" @click="showFilterOptions">
          <text class="filter-icon">⚙️</text>
        </view>
      </template>
    </uni-nav-bar>

    <!-- 筛选条件 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          class="filter-tab"
          :class="{ active: activeFilter === 'all' }"
          @click="switchFilter('all')"
        >
          全部订单
        </view>
        <view 
          class="filter-tab"
          :class="{ active: activeFilter === 'completed' }"
          @click="switchFilter('completed')"
        >
          已完成
        </view>
        <view 
          class="filter-tab"
          :class="{ active: activeFilter === 'cancelled' }"
          @click="switchFilter('cancelled')"
        >
          已取消
        </view>
      </view>
      
      <!-- 时间筛选 -->
      <view class="time-filter">
        <view class="time-range" @click="showTimePicker">
          <text class="time-text">{{ selectedTimeRange }}</text>
          <text class="arrow-icon">▼</text>
        </view>
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="orders-container">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载历史订单中...</text>
      </view>
      
      <!-- 订单卡片列表 -->
      <view 
        v-for="order in filteredOrders"
        :key="order.id"
        class="order-card"
        @click="viewOrderDetail(order.id)"
      >
        <!-- 订单头部信息 -->
        <view class="order-header">
          <view class="order-info">
            <text class="order-number">订单编号: {{ order.orderNumber }}</text>
            <text class="order-time">{{ order.createTime }}</text>
          </view>
          <view class="order-status" :class="order.status">
            {{ getStatusText(order.status) }}
          </view>
        </view>

        <!-- 订单标题和详情 -->
        <view class="order-content">
          <text class="order-title">{{ order.title }}</text>
          <text class="order-desc">{{ order.description }}</text>
        </view>

        <!-- 送达信息 -->
        <view class="delivery-info">
          <view class="location-item">
            <text class="location-label">取货地址:</text>
            <text class="location-text">{{ order.pickupAddress }}</text>
          </view>
          <view class="location-item">
            <text class="location-label">送达地址:</text>
            <text class="location-text">{{ order.deliveryAddress }}</text>
          </view>
        </view>

        <!-- 数据信息区域 -->
        <view class="data-section">
          <view class="data-row">
            <view class="data-item">
              <text class="data-label">姓名</text>
              <text class="data-value">{{ order.customerName }}</text>
            </view>
            <view class="data-item">
              <text class="data-label">电话</text>
              <text class="data-value phone" @click.stop="makePhoneCall(order.customerPhone)">
                {{ order.customerPhone }}
              </text>
            </view>
          </view>
          <view class="data-row">
            <view class="data-item">
              <text class="data-label">加价金额</text>
              <text class="data-value extra">+¥{{ order.extraAmount }}</text>
            </view>
            <view class="data-item">
              <text class="data-label">实际收入</text>
              <text class="data-value income">¥{{ order.actualIncome }}</text>
            </view>
          </view>
        </view>

        <!-- 骑手信息 -->
        <view class="rider-section" v-if="order.rider">
          <view class="rider-info">
            <image :src="order.rider.avatar" class="rider-avatar" />
            <view class="rider-details">
              <text class="rider-name">{{ order.rider.name }}</text>
              <text class="rider-phone">{{ order.rider.phone }}</text>
            </view>
            <view class="contact-btn" @click.stop="contactRider(order.rider)">
              联系
            </view>
          </view>
        </view>

        <!-- 订单操作按钮 -->
        <view class="order-actions">
          <button 
            class="action-btn secondary" 
            @click.stop="viewOrderDetail(order.id)"
          >
            查看详情
          </button>
          <button 
            v-if="order.status === 'completed'"
            class="action-btn primary" 
            @click.stop="reviewOrder(order.id)"
          >
            评价订单
          </button>
          <button 
            v-if="order.canReorder"
            class="action-btn primary" 
            @click.stop="reorderOrder(order.id)"
          >
            再次下单
          </button>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && filteredOrders.length === 0">
        <view class="empty-icon">
          <text class="empty-emoji">📋</text>
        </view>
        <text class="empty-text">{{ getEmptyText() }}</text>
        <button class="go-order-btn" @click="goToOrderHall">
          去抢单大厅看看
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

// 声明uni全局变量
declare const uni: any

// 订单状态类型
type OrderStatus = 'pending' | 'accepted' | 'in_progress' | 'completed' | 'cancelled'

// 历史订单数据类型
interface HistoryOrder {
  id: number
  orderNumber: string
  title: string
  description: string
  pickupAddress: string
  deliveryAddress: string
  customerName: string
  customerPhone: string
  extraAmount: string
  actualIncome: string
  status: OrderStatus
  createTime: string
  completeTime?: string
  canReorder: boolean
  rider?: {
    name: string
    phone: string
    avatar: string
  }
}

// 响应式数据
const loading = ref(false)
const activeFilter = ref<'all' | 'completed' | 'cancelled'>('all')
const selectedTimeRange = ref('最近一个月')
const historyOrders = ref<HistoryOrder[]>([])

// 计算属性：过滤后的订单
const filteredOrders = computed(() => {
  if (activeFilter.value === 'all') {
    return historyOrders.value
  }
  return historyOrders.value.filter(order => {
    if (activeFilter.value === 'completed') {
      return order.status === 'completed'
    }
    if (activeFilter.value === 'cancelled') {
      return order.status === 'cancelled'
    }
    return true
  })
})

// 页面加载时获取历史订单
onMounted(() => {
  loadHistoryOrders()
})

// 加载历史订单数据
const loadHistoryOrders = async () => {
  loading.value = true
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟历史订单数据
    historyOrders.value = [
      {
        id: 1,
        orderNumber: 'JJK202401001',
        title: '万能任务【帮拿外卖】',
        description: '请在下方描述外卖具体信息',
        pickupAddress: '科技东院—图书馆',
        deliveryAddress: '理工科技校园网吧',
        customerName: '免疫',
        customerPhone: '13483231011',
        extraAmount: '2.00',
        actualIncome: '4.82',
        status: 'completed',
        createTime: '2024-01-15 17:30',
        completeTime: '2024-01-15 18:00',
        canReorder: true,
        rider: {
          name: '小李',
          phone: '13812345678',
          avatar: '/static/images/avatar1.png'
        }
      },
      {
        id: 2,
        orderNumber: 'JJK202401002',
        title: '代取快递',
        description: '帮忙取圆通快递',
        pickupAddress: '东门快递站',
        deliveryAddress: '学生宿舍5号楼',
        customerName: '小明',
        customerPhone: '13987654321',
        extraAmount: '1.50',
        actualIncome: '3.50',
        status: 'completed',
        createTime: '2024-01-14 15:20',
        completeTime: '2024-01-14 16:10',
        canReorder: false
      },
      {
        id: 3,
        orderNumber: 'JJK202401003',
        title: '帮买奶茶',
        description: '一点点奶茶店购买',
        pickupAddress: '学校奶茶店',
        deliveryAddress: '图书馆3楼',
        customerName: '小红',
        customerPhone: '13765432109',
        extraAmount: '0.00',
        actualIncome: '2.00',
        status: 'cancelled',
        createTime: '2024-01-13 14:00',
        canReorder: true
      }
    ]
  } catch (error) {
    console.error('加载历史订单失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'error'
    })
  } finally {
    loading.value = false
  }
}

// 获取状态文本
const getStatusText = (status: OrderStatus): string => {
  const statusMap = {
    'pending': '待接单',
    'accepted': '已接单',
    'in_progress': '进行中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status]
}

// 获取空状态提示文本
const getEmptyText = (): string => {
  const textMap = {
    'all': '暂无历史订单',
    'completed': '暂无已完成的订单',
    'cancelled': '暂无已取消的订单'
  }
  return textMap[activeFilter.value]
}

// 方法
const goBack = () => {
  uni.navigateBack()
}

const switchFilter = (filter: 'all' | 'completed' | 'cancelled') => {
  activeFilter.value = filter
}

const showFilterOptions = () => {
  uni.showActionSheet({
    itemList: ['按时间排序', '按金额排序', '导出订单'],
    success: (res: any) => {
      if (res.tapIndex === 0) {
        // 按时间排序
        historyOrders.value.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())
      } else if (res.tapIndex === 1) {
        // 按金额排序
        historyOrders.value.sort((a, b) => parseFloat(b.actualIncome) - parseFloat(a.actualIncome))
      } else if (res.tapIndex === 2) {
        // 导出订单
        uni.showToast({
          title: '导出功能开发中',
          icon: 'none'
        })
      }
    }
  })
}

const showTimePicker = () => {
  uni.showActionSheet({
    itemList: ['最近一周', '最近一个月', '最近三个月', '全部时间'],
    success: (res: any) => {
      const timeRanges = ['最近一周', '最近一个月', '最近三个月', '全部时间']
      selectedTimeRange.value = timeRanges[res.tapIndex]
      // 这里可以根据选择的时间范围重新加载数据
    }
  })
}

const viewOrderDetail = (orderId: number) => {
  uni.navigateTo({
    url: `/pages/JJK/order-detail?id=${orderId}`
  })
}

const makePhoneCall = (phoneNumber: string) => {
  uni.makePhoneCall({
    phoneNumber: phoneNumber
  })
}

const contactRider = (rider: any) => {
  uni.showActionSheet({
    itemList: ['拨打电话', '发送短信'],
    success: (res: any) => {
      if (res.tapIndex === 0) {
        uni.makePhoneCall({
          phoneNumber: rider.phone
        })
      } else if (res.tapIndex === 1) {
        uni.showToast({
          title: '短信功能开发中',
          icon: 'none'
        })
      }
    }
  })
}

const reviewOrder = (orderId: number) => {
  uni.showToast({
    title: '评价功能开发中',
    icon: 'none'
  })
}

const reorderOrder = (orderId: number) => {
  uni.showModal({
    title: '确认下单',
    content: '确定要重新下单吗？',
    success: (res: any) => {
      if (res.confirm) {
        uni.showToast({
          title: '下单成功',
          icon: 'success'
        })
      }
    }
  })
}

const goToOrderHall = () => {
  uni.navigateTo({
    url: '/pages/JJK/qiang'
  })
}
</script>

<style lang="scss" scoped>
.history-orders-page {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.nav-right {
  display: flex;
  align-items: center;
  padding: 0 10px;
  
  .filter-icon {
    font-size: 18px;
    color: #666;
  }
}

.filter-section {
  background-color: #fff;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  
  .filter-tabs {
    display: flex;
    gap: 20px;
    margin-bottom: 15px;
    
    .filter-tab {
      padding: 8px 16px;
      border-radius: 20px;
      background-color: #f8f9fa;
      color: #666;
      font-size: 14px;
      transition: all 0.2s ease;
      
      &.active {
        background-color: #007aff;
        color: #fff;
      }
    }
  }
  
  .time-filter {
    .time-range {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px 15px;
      background-color: #f8f9fa;
      border-radius: 8px;
      
      .time-text {
        font-size: 14px;
        color: #333;
      }
      
      .arrow-icon {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

.orders-container {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  
  .loading-spinner {
    width: 30px;
    height: 30px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #007aff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 16px;
  }
  
  .loading-text {
    font-size: 14px;
    color: #666;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.order-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 15px;
    
    .order-info {
      .order-number {
        display: block;
        font-size: 14px;
        color: #333;
        font-weight: 600;
        margin-bottom: 4px;
      }
      
      .order-time {
        font-size: 12px;
        color: #999;
      }
    }
    
    .order-status {
      padding: 4px 12px;
      border-radius: 15px;
      font-size: 12px;
      font-weight: 500;
      
      &.completed {
        background-color: #e8f5e8;
        color: #388e3c;
      }
      
      &.cancelled {
        background-color: #ffebee;
        color: #d32f2f;
      }
      
      &.pending {
        background-color: #fff3e0;
        color: #f57c00;
      }
    }
  }
  
  .order-content {
    margin-bottom: 15px;
    
    .order-title {
      display: block;
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 6px;
    }
    
    .order-desc {
      font-size: 14px;
      color: #666;
      line-height: 1.4;
    }
  }
  
  .delivery-info {
    margin-bottom: 15px;
    
    .location-item {
      display: flex;
      margin-bottom: 6px;
      
      .location-label {
        font-size: 14px;
        color: #666;
        min-width: 70px;
      }
      
      .location-text {
        flex: 1;
        font-size: 14px;
        color: #333;
      }
    }
  }
  
  .data-section {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    
    .data-row {
      display: flex;
      gap: 20px;
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .data-item {
        flex: 1;
        
        .data-label {
          display: block;
          font-size: 12px;
          color: #999;
          margin-bottom: 4px;
        }
        
        .data-value {
          font-size: 14px;
          font-weight: 600;
          color: #333;
          
          &.phone {
            color: #007aff;
            text-decoration: underline;
          }
          
          &.extra {
            color: #ff9500;
          }
          
          &.income {
            color: #34c759;
          }
        }
      }
    }
  }
  
  .rider-section {
    margin-bottom: 15px;
    
    .rider-info {
      display: flex;
      align-items: center;
      padding: 10px 15px;
      background-color: #f0f9ff;
      border-radius: 8px;
      
      .rider-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        margin-right: 12px;
        background-color: #e5e7eb;
      }
      
      .rider-details {
        flex: 1;
        
        .rider-name {
          display: block;
          font-size: 14px;
          font-weight: 600;
          color: #333;
          margin-bottom: 2px;
        }
        
        .rider-phone {
          font-size: 12px;
          color: #666;
        }
      }
      
      .contact-btn {
        padding: 6px 12px;
        background-color: #007aff;
        color: #fff;
        border-radius: 15px;
        font-size: 12px;
      }
    }
  }
  
  .order-actions {
    display: flex;
    gap: 10px;
    
    .action-btn {
      flex: 1;
      padding: 10px 16px;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      
      &.primary {
        background-color: #007aff;
        color: #fff;
      }
      
      &.secondary {
        background-color: #f8f9fa;
        color: #333;
        border: 1px solid #e5e7eb;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  
  .empty-icon {
    width: 120px;
    height: 120px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .empty-emoji {
      font-size: 60px;
      opacity: 0.6;
    }
  }
  
  .empty-text {
    font-size: 16px;
    color: #999;
    margin-bottom: 30px;
  }
  
  .go-order-btn {
    padding: 12px 24px;
    background-color: #007aff;
    color: #fff;
    border: none;
    border-radius: 25px;
    font-size: 16px;
    font-weight: 500;
  }
}
</style>

